﻿using AutoMapper;
using MediatR;
using RedDragon.Common.Domain.Purchase;
using RedDragon.Common.Infrastructure.Interface;
using RedDragon.ERP.ErroCodeEnum;
using T.Common.Domain.Common;

namespace RedDragon.ERP.API.Application.Commands.Purchases
{
    /// <summary>
    /// 添加付款计划行信息
    /// </summary>
    public class CreatePaymentHandler : IRequestHandler<CreatePaymentCommand, Result>
    {
        /// <summary>
        /// Mapper类
        /// </summary>
        private readonly IMapper _mapper;

        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<CreatePaymentHandler> _logger;

        /// <summary>
        /// 订单行仓储
        /// </summary>
        private readonly IBaseRepository<Payments> _paymentsRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="logger"></param>
        /// <param name="paymentsRepository"></param>
        public CreatePaymentHandler(IMapper mapper,
            ILogger<CreatePaymentHandler> logger,
            IBaseRepository<Payments> paymentsRepository)
        {
            _mapper = mapper;
            _logger = logger;
            _paymentsRepository = paymentsRepository;
        }

        /// <summary>
        /// 添加付款计划行信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(CreatePaymentCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Added };
            try
            {
                //mapper转换
                var payment = _mapper.Map<Payments>(request);
                var res = await _paymentsRepository.Add(payment);
                if (res > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Msg = "添加付款计划行信息成功";
                }
            }
            catch (Exception ex)
            {
                result.Msg = "添加付款计划行信息异常" + ex.Message;
                _logger.LogError("添加付款计划行信息异常" + ex.Message);
            }
            return result;
        }
    }
}
